package com.baogu.factoryjob.job;

import com.baogu.factoryjob.service.JobService;
import com.baogu.factoryjob.service.impl.TaskServiceImpl;
import com.baogu.model.job.JobManage;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class JobFeactory {

    @Autowired
    JobService jobService;
    @Autowired
    TaskServiceImpl taskServiceImpl;
    private static boolean isRun = true;

    private Logger logger = LogManager.getLogger(getClass());

    @Scheduled(initialDelay=1000, fixedRate=5000)
    public void lodingJob() {
        JobManage jobManage = new JobManage();
        jobManage.setState(1);
        List<JobManage> list = jobService.getJobList(jobManage);
        try {
            if(isRun){
                for (JobManage job : list){
                    System.out.println(job);
                    taskServiceImpl.addJob(job);
                }
                isRun = false;
            }
            else{
                updateJob(list);
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void updateJob(List<JobManage> list) throws SchedulerException, ClassNotFoundException {
        if(list == null || list.size() == 0){
            return;
        }
        Map<String,JobManage> map = taskServiceImpl.getMap();
        for (JobManage jobManage:list){
            if(!map.containsKey(jobManage.getId())){
                taskServiceImpl.addJob(jobManage);
            }
            if(jobManage.equals(map.get(jobManage.getId()))){
                continue;
            }
            else{
                taskServiceImpl.edit(jobManage);
            }

        }
    }
}
